package cn.tedu._03vehicle.base.excepetion;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

//全局异常处理器
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    //1演示全局异常处理器的使用
    @ExceptionHandler(IllegalArgumentException.class)//
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex){
        String data=ex.getMessage();
        log.error("IllegalArgumentException="+data);
//
        return JsonResult.failed(data);
    }
    //2封装参数的异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data=ex.getMessage();
        log.error("ConstrainViolationException:"+data);
        return new JsonResult(StatusCode.VALIDATED_ERRROR,data);
    }
    //3非封装参数出先的异常
    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult doHandleConstrainViolationException(ConstraintViolationException ex){
        //delete id 车辆id必须在1-500之间
        String data=ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException"+data);
        return new JsonResult(StatusCode.VALIDATED_ERRROR,data);
    }
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public JsonResult doHandleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex){
        String data="单个文件上传大小不超过100MB，单次多个文件提交不超过500MB";
        log.error("MaxUploadSizeExceededException"+data);
        return new JsonResult(StatusCode.FILE_SIZE_ERROR,data);
    }








    //父类异常处理
    @ExceptionHandler(RuntimeException.class)
    public JsonResult doHandleRuntimeException(RuntimeException ex){
        String data = ex.getMessage();
        log.error("RuntimeException:" + data);

        return JsonResult.failed(data);
    }
    /**
     *  能处理所有异常的处理方法 一般放在最后
     */
//    @ExceptionHandler(Throwable.class)
//   public JsonResult dohandleThrowable(Throwable ex){
//       String data=ex.getMessage();
//       log.error("Throwable"+data);
//       return new JsonResult(StatusCode.THROWABLE_ERROR);
//   }



}
